import { takeEvery } from 'redux-saga';
import { call, put, fork, take, select } from 'redux-saga/effects';
import { hashHistory } from 'react-router';
import { Toast, Modal } from 'antd-mobile';

import Api from '../../api'

import {
  GET_ORDERS_SUCCESS
} from '../actions';

// 注册验证
 function* do_get_user({ payload }){
   try{
     yield put({ type:SET_USER_TYPE, payload });

     Toast.loading('加载中...')
     const res = yield call(Api.getUser, payload);
     Toast.hide();

     if(res.errorCode === 401){
        // 未注册，跳转到注册页
        const userType = yield select(state => state.app.userType);
        hashHistory.push({ pathname:'register', search: `?type=${userType}`});
      }else if(res.errorCode === 200){
        // 已注册
        yield put({
          type: SUCCESS_GET_USER,
          payload: res
        })
      }else{
        Toast.info(res.moreInfo || '未知错误', 3);
      }

   }catch(e){
     // 请求用户信息失败
     Toast.hide();
   }
 }

// 注册
function* do_create_user({ payload }){
  try{
    Toast.loading('加载中...')
    const result = yield call(Api.createUser, payload);
    Toast.hide();

    if(result.errorCode === 200){
      // 已经注册，跳转到首页
      Modal.alert('系统提示', result.moreInfo, [{text:'前往首页',onPress:()=>{
        hashHistory.push({ pathname:'/', search: `?type=${payload.type}` });
      }}])
    }else{
      debugger;
      // 注册失败，显示失败信息
      Toast.info(result.moreInfo || '未知错误', 3);
    }
  }catch(err){
    yield put({type: FAILURE_CREATE_USER, payload: err});
    Toast.hide();
  }
}

function* watch_user_create(){
  yield* takeEvery(REQUEST_CREATE_USER, do_create_user);
}

function* watch_get_user(){
  yield* takeEvery(REQUEST_GET_USER, do_get_user);
}

// function* watch_user_update(){
//
// }

export default function* sagas() {
  yield fork(watch_user_create);
  yield fork(watch_get_user);
}
